const fs = require('fs')
const Epub = require('./epub')

const MIME_TYPE_EPUB = 'application/epub+zip'
class eBook {
  constructor(file) {
    const {
      destination: des, // 文件本地存储目录
      filename, // 文件名称
      path,
      mimetype = MIME_TYPE_EPUB // 文件资源类型
    } = file
    const suffix = mimetype === MIME_TYPE_EPUB ? '.epub' : ''
    const file_path = `${des}/${filename}${suffix}`
    if (fs.existsSync(path) && !fs.existsSync(file_path)) {
      fs.renameSync(path, file_path) // 重命名文件
    }

    this.filename = filename // 文件名
    this.title = '' // 标题
    this.language = '' // 语种
    this.author = '' // 作者
    this.publisher = '' // 出版社
    this.category = '' // 分类
    this.description = '' //简介
    this.file_path = `/book/${filename}${suffix}` // epub文件路径
    this.cover_path = '' // 封面图片
  }

  parse() {
    return new Promise((resolve, reject) => {
      const bookPath = `${process.env.UPLOAD_PATH}${this.file_path}`
      if (!this.file_path || !fs.existsSync(bookPath)) {
        reject(new Error('电子书路径不存在'))
      }
      const epub = new Epub(bookPath)
      epub.on('error', err => {
        reject(err)
      })
      epub.on('end', err => {
        if (err) {
          reject(err)
        } else {
          let {
            title,
            language,
            creator,
            creatorFileAs,
            publisher,
            description,
            subject,
            cover
          } = epub.metadata

          if (!title) {
            reject(new Error('图书标题为空'))
          } else {
            this.title = title
            this.language = language || 'en'
            this.author = creator || creatorFileAs || 'unknown'
            this.publisher = publisher || 'unknown'
            this.category = subject || 'unknown'
            this.description = description || 'unknown'

            const getCover = (error, img, mimeType) => {
              if (error) {
                reject(error)
              } else {
                const suffix = mimeType.split('/')[1]
                if (!fs.existsSync(`${process.env.UPLOAD_PATH}/cover`)) {
                  fs.mkdirSync(`${process.env.UPLOAD_PATH}/cover`, {
                    recursive: true
                  }) // 创建保存电子书封面的目录
                }
                const cover_path = `${process.env.UPLOAD_PATH}/cover/${this.filename}.${suffix}`
                fs.writeFileSync(cover_path, img, 'binary')
                this.cover_path = `/cover/${this.filename}.${suffix}`
                resolve(this)
              }
            }
            try {
              epub.getImage(cover, getCover) // 获取封面图片
            } catch (e) {
              reject(e)
            }
          }
        }
      })
      epub.parse()
    })
  }
}

module.exports = {
  eBook
}
